package lihua.robot.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PostManUtil {

    /**
     * 调用运单接口
     * @param id
     * @param blocks
     * @return
     */
    public static JSONObject sendBlocksPost(String id, List<Map<String, Object>> blocks, String robtName) {
        String URL = "http://localhost:8088/setOrder";
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(URL);
            httpPost.addHeader("Content-type", "application/json");

            JSONObject json = new JSONObject();
            json.put("id", id);
            json.put("priority", 10);
            json.put("blocks", blocks);
            json.put("vehicle", robtName);
            json.put("complete", true);

            StringEntity se = new StringEntity(json.toString(), "UTF-8");
            httpPost.setEntity(se);

            HttpResponse response = httpClient.execute(httpPost);
            System.out.println("Response status code: " + response.getStatusLine().getStatusCode());

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonResponse = JSONObject.fromObject(result);
                System.out.println("API response data: " + jsonResponse.toString());
                return jsonResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            // Here, consider logging the exception or handling it appropriately
        }
        return new JSONObject(); // Consider returning null or a meaningful empty object depending on your use case
    }


    public static net.sf.json.JSONObject sendPowerPost(List<Map<String,Object>> vehicles){
        //定义接口
        String URL = "http://localhost:8088/lock";
        //创建连接对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //post请求
        HttpPost httpPost = new HttpPost(URL);
        //参数拼接
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for(int i=0; i<5; i++){
            NameValuePair valuePair = new BasicNameValuePair("key"+i,"value"+i);
            list.add(valuePair);
        }
        try {
            //请求报文
            httpPost.addHeader("Content-type","application/x-www-form-urlencoded");
            // 参数
            JSONObject json = new JSONObject();
            json.put("vehicles",vehicles);


            // 设置参数到请求对象中
            StringEntity se = new StringEntity(json.toString(), "UTF-8");
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPost.setEntity(se);

            //发送请求
            HttpResponse response = httpClient.execute(httpPost);

            System.out.println("获取返回服务器的状态码：----- "+response.getStatusLine().getStatusCode());



            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //成功后响应数据
                String result = EntityUtils.toString(response.getEntity());
                net.sf.json.JSONObject json1 = net.sf.json.JSONObject.fromObject(result);
                System.out.println("接口返回数据："+json1.toString());
                return json1;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                //释放连接
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new net.sf.json.JSONObject();
    }

    public static net.sf.json.JSONObject sendReleasePowerPost(List<Map<String,Object>> vehicles){
        //定义接口
        String URL = "http://localhost:8088/unlock";
        //创建连接对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //post请求
        HttpPost httpPost = new HttpPost(URL);
        //参数拼接
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for(int i=0; i<5; i++){
            NameValuePair valuePair = new BasicNameValuePair("key"+i,"value"+i);
            list.add(valuePair);
        }
        try {
            //请求报文
            httpPost.addHeader("Content-type","application/x-www-form-urlencoded");
            // 参数
            JSONObject json = new JSONObject();
            json.put("vehicles",vehicles);


            // 设置参数到请求对象中
            StringEntity se = new StringEntity(json.toString(), "UTF-8");
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPost.setEntity(se);

            //发送请求
            HttpResponse response = httpClient.execute(httpPost);

            System.out.println("获取返回服务器的状态码：----- "+response.getStatusLine().getStatusCode());



            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //成功后响应数据
                String result = EntityUtils.toString(response.getEntity());
                net.sf.json.JSONObject json1 = net.sf.json.JSONObject.fromObject(result);
                System.out.println("接口返回数据："+json1.toString());
                return json1;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                //释放连接
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new net.sf.json.JSONObject();
    }

    public static String getOrderDetails(String orderId) {
        try {
            String URL = "http://localhost:8088/orderDetails/" + orderId.replace(" ", "%20").replace(":", "%3A");

            try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
                HttpGet httpGet = new HttpGet(URL);
                httpGet.addHeader("Accept", "application/json");

                HttpResponse response = httpClient.execute(httpGet);
                System.out.println("获取返回服务器的状态码：----- " + response.getStatusLine().getStatusCode());

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject jsonResponse = JSONObject.fromObject(result);
                    return jsonResponse.getString("state");
                } else {
                    // 打印错误状态码
                    System.out.println("Error response code: " + response.getStatusLine().getStatusCode());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null; // 或者返回一个适当的值，取决于你的需求
    }
}
